package org.tungse.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.tungse.controller.UserController;
import org.tungse.service.UserService;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author : Tungse
 * @Date: 2025/7/2 10:53
 * @Description:
 */

@Configuration
public class SentinelAspectConfiguration {
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    //初始化限流规则
    //定义了每秒最多接收2个请求
    @PostConstruct
    public  void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule(UserController.RESOURCE_NAME);
        // set limit qps to 2
        rule.setCount(2);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setLimitApp("default");
        rules.add(rule);

        FlowRule rule1 = new FlowRule(UserController.RESOURCE_NAME_QUERY_USER_BY_ID);
        // set limit qps to 2
        rule1.setCount(2);
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setLimitApp("default");
        rules.add(rule1);

        FlowRule rule2 = new FlowRule("AAAAAAAAAAAA");
        // set limit qps to 2
        rule2.setCount(2);
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule2.setLimitApp("default");
        rules.add(rule2);


        FlowRule rule3 = new FlowRule(UserService.RESOURCE_NAME_QUERY_USER_BY_NAME);
        // set limit qps to 2
        rule3.setCount(2);
        rule3.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule3.setLimitApp("default");
        rules.add(rule3);


        FlowRuleManager.loadRules(rules);
    }
}